<?php

namespace PHD;

class Lib {
    
    // "\n\n" or "\r\n\r\n" End of Message
    public static function EoM($msg) {
        
        $len = strlen($msg);
        
        $pos = strpos($msg, "\n\n");

        if ($pos !== false) {
            if ($pos == $len - 2) 
                return true;
        }

        $pos = strpos($msg, "\r\n\r\n");

        if ($pos !== false) {
            if ($pos == $len - 4) 
                return true;
        }
        
        return false;

    }
    
    //Parse Client Message
    public static function PCM($msg){

        $parts = explode("\n", $msg, 2);
        $method_parts = trim($parts[0]);
        list( $method['request_method'],
              $method['uri'],
              $method['version']        ) = explode(" ", $method_parts);

        $headers_parts = explode("\n", trim($parts[1]));
        foreach ($headers_parts as $header) {
            list($name, $value) = explode(":", $header, 2);
            $headers[$name] = trim($value);
        }

        $request['method'] = $method;
        $request['headers'] = $headers;

        return $request;

    }
    
    public static function URI2FS($msg){
        
        $config = Config::getInstance();
        if ($msg === '/')
            $path = $config->wwwroot . $msg . $config->indexfile;
        else
            $path = $config->wwwroot . $msg;
        
        return $path;
    }
    
}
